package edu.sdcet.m10d1302.Controller;

import edu.sdcet.m10d1302.Entity.Student;
import edu.sdcet.m10d1302.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class StudentController {

    @Autowired
    StudentService studentService;

    // 1.获取所有学生信息
    @GetMapping(value = "/getAllStudents", produces = "application/json")
    public List<Student> getAllStudents(){
        List<Student> students = studentService.getAllStudents();
        return students;
    }

    // 2.根据学号查询单个学生的信息
    @GetMapping(value = "/getStudentById/{studentId}", produces = "application/json")
    public Student getStudentById(@PathVariable("studentId") String studentId){
        return studentService.getStudentById(studentId);
    }

    // 3.根据学号修改学生信息
    @PostMapping(value = "/updateStudent", produces = "application/json")
    public Map<String, Object> updateStudent(@RequestBody Student student){
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("更新学生信息：student="+student);
            studentService.updateStudent(student);
            result.put("success", true);
            result.put("message", "学生信息更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "学生信息更新失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 4.新增一个学生信息
    @PostMapping(value = "/addStudent", produces = "application/json")
    public Map<String, Object> addStudent(@RequestBody Student student){
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("新增学生信息：student="+student);
            studentService.addStudent(student);
            result.put("success", true);
            result.put("message", "添加学生信息成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加学生信息失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 5.根据学号删除（物理）某个同学的信息
    @DeleteMapping(value = "/deleteStudent/{studentId}", produces = "application/json")
    public Map<String, Object> deleteStudent(@PathVariable("studentId") String studentId){
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("新增学生信息：studentid="+ studentId);
            studentService.deleteStudent(studentId);
            result.put("success", true);
            result.put("message", "添加学生信息成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加学生信息失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
